#!/usr/bin/env node

/**
 * @description cli 的入口文件
 * @author fyj
 */

const inquirer = require('inquirer');
const path = require('path');
const ejs = require('ejs');
const fs = require('fs');
const pkgName = require(`${process.cwd()}/package.json`);

// 1. 用户命令行的交互
inquirer.prompt([
  {
    type: 'input',
    name: 'name',
    message: 'input package name:',
    default: pkgName.name
  }, {
    type: 'input',
    name: 'path',
    message: '请输入生成的文件存储的目录：',
    default: '.'
  }
])
  .then(answers => {
    // 文件夹和文件的生成
    const dir = [
      'bin',
      'test',
      'dist',
      'doc',
      'src',
      'src/conf',
      'src/controller',
      'src/db',
      'src/model',
      'src/public',
      'src/public/css',
    ];
    const file = [
      'README.md',
      'bin/www.js',
      'src/public/index.html',
      'src/public/css/index.css',
      'src/app.js',
    ];

    // 创建文件夹
    dir.forEach(item => {
      const destPath = path.resolve(process.cwd(), answers.path, item);
      fs.mkdirSync(destPath);
    })
    // 写入文件
    file.forEach(item => {
      // 使用数据填充文件
      const filePath = path.resolve(__dirname, 'templates', item);
      ejs.renderFile(filePath, { name: answers.name }, (err, result) => {
        if(err) {
          console.error('ejs 渲染模板出错');
          return;
        }
        // 写文件
        const destPath = path.resolve(process.cwd(), answers.path, item);
        fs.writeFileSync(destPath, result);
      })
    })
  })
  .catch(err => {
    console.error('^|-|^ 失败了');
  })
